package hgx.spring.cloud.lession.myhystrix;/**
 * Created by liujun on 2018/4/19.
 */

/**
 * 断路器管理
 *
 * @author Administrator
 * @create 2018-04-19 14:08
 */
public class MyHystrixManager {

    private static MyHystrixManager insance;

    private final int requestTotaleCount = 5; //支持并发处理总请求数阀值
    private final int failTotaleCount = 3; //支持并发处理总失败数阀值，超过这个阀值，则关闭断路器
    private volatile int requestCount = 0; //请求处理计数器
    private volatile int failCount = 0; //处理失败计数器
    private volatile boolean openStatus = false; //断路器开关状态 ，true - 打开 ，false - 关闭
    protected static final int Handler_Time_Out= 500; //处理请示超时时间阀值，单位： 毫秒

    private MyHystrixManager() {
    }

    public static synchronized MyHystrixManager getInsance() {
        if (insance == null) {
            insance = new MyHystrixManager();
        }

        return insance;
    }

    /**
     * 是否允许访问服务，即是否超过信号量
     * 处理逻辑：
     * 1、断路器未打开，且当前请求数量已超过信号量阀值
     *
     * @return
     */
    protected boolean isAllowRequest() {
        if (this.requestCount > this.requestTotaleCount) {
            return false;
        }
        this.requestCount++;
        return true;
    }

    /**
     * 该命令key是否有缓存
     *
     * @param commandKeyType
     * @return true - 有缓存， 反之为false
     */
    protected boolean isCache(MyCommandKeyType commandKeyType) {
        return false;
    }

    /**
     * 断路器是否打开
     *
     * @return true - 打开，反之为false
     */
    protected boolean isOpen() {
        return openStatus;
    }

    /**
     * 修改失败次数
     *
     * @param success
     */
    protected void updateFailCount(boolean success) {
        if (success) {
            this.failCount++;
        } else {

            if (this.failCount <= 0) {
                this.failCount = 0;
            } else {
                this.failCount--;
            }
        }

        if (this.failCount > this.failTotaleCount) {
            openStatus = true;
        } else {
            openStatus = false;
        }
    }

}
